package xdu.lz.stage5_jucUtils.chapter6_forkjointask;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

/**
 * Created at 2019/10/20 0020 下午 3:08
 *
 * abstract :ForkJoinTask
 * abstract      -->RecursiveTask 有返回值
 * abstract      -->RecursiveAction Void
 * 由ForkJoinPool调用管理
 *
 */
public class ForkJoinRecursiveTask {

    /**
     * Demo：做累加动作，分布式多线程并行执行。一个线程最多累加MAX_SINGLE_COUNT个，然后合并
     *
     *
     */
    private static long MAX_SINGLE_COUNT = Long.MAX_VALUE;

    //一般继承RecursiveTask或RecursiveAction实现compute方法，由ForkJoinPool调用submit传进去
    private static class CalculationTask extends RecursiveTask<Long>{

        private final long start;

        private final long end;

        private CalculationTask(long start, long end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            if(end - start <= MAX_SINGLE_COUNT){
                return LongStream.rangeClosed(start,end).sum();
            }else {
                long mid = (start + end) >> 1;
                CalculationTask leftTask = new CalculationTask(start, mid);
                CalculationTask rightTask = new CalculationTask(mid+1, end);
                leftTask.fork();
                rightTask.fork();
                return leftTask.join() + rightTask.join();
            }
        }
    }


    public static void main(String[] args) {
        ForkJoinPool joinPool = new ForkJoinPool();
        ForkJoinTask<Long> future = joinPool.submit(new CalculationTask(1, 100000000));
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
